﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using SpLocalizer.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using System.Xml;

namespace SpLocalizer.ContentSourceProviders.SpTaxonomy
{
    public class SpTermLocalizationTask : BaseTranslationTask
    {

        #region Constants
        
        private const string Property_TermId = "TermId";

        #endregion


        /// <summary>
        /// Term idemtifier
        /// </summary>
        public Guid TermId
        {
            get { return new Guid(this.GetPropertyValue(Property_TermId)); }
            set { this.SetPropertyValue(Property_TermId, value.ToString()); }
        }


      /// <summary>
        /// Constructor without parameters should be public for unity injection
        /// </summary>
        public SpTermLocalizationTask() { }

        internal SpTermLocalizationTask(CultureInfo FromLanguage, CultureInfo ToLanguage,
            Term term)
            : base(FromLanguage, ToLanguage)
        {

            this.TermId = term.Id;
            Label lblFrom = term.Labels.Where<Label>(lbl => lbl.Language == FromLanguage.LCID).FirstOrDefault<Label>();
            if (lblFrom != null)
            {
                this.SourceText = lblFrom.Value;
                this.Status = TranslationTaskStatus.Initialized;
            }

            // Check if label already translated
            Label toLable = term.Labels.Where<Label>(lbl => lbl.Language == ToLanguage.LCID).FirstOrDefault<Label>();
            if (toLable != null && !String.IsNullOrEmpty(toLable.Value))
            {
                this.TranslatedText = toLable.Value;
                this.Status = TranslationTaskStatus.Canceled; //We don't need dubplicate our job
            }

        }

        internal void UpdateLabel(Term term)
        {
            // Check if label already translated
            Label toLable = term.Labels.Where<Label>(lbl => lbl.Language == ToLanguage.LCID).FirstOrDefault<Label>();
            if (toLable == null)
            {
                toLable = term.CreateLabel(this.TranslatedText, ToLanguage.LCID, false);
            }
            else
            {
                toLable.Value = this.TranslatedText;
            }

            //toLable.SetAsDefaultForLanguage();
            try
            {
                term.TermStore.CommitAll();
            }
            catch (Microsoft.SharePoint.Taxonomy.TermStoreOperationException)
            {
                //Do nothing: Looks like we don't translate this term
            }

        }

    }
}
